package 网络编程.TCPFileCopy1;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-05
 * Time: 17:34
 */
public class TCPFileClint01 {

    Socket socket = null;

    public TCPFileClint01() throws IOException {
        socket = new Socket("127.0.0.1",8000);
    }

    public void start() throws IOException {
        System.out.println("客户端启动...");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            //用户输入你要下载的文件名是啥
            Scanner scan = new Scanner(System.in);
            String fileName = scan.next();
            //客户端将想要下载的文件名发送给服务器
            BufferedOutputStream bufferedOutputStream =
                    new BufferedOutputStream(outputStream);
            //发送给服务器
            bufferedOutputStream.write(fileName.getBytes());
            bufferedOutputStream.flush();
            socket.shutdownOutput();
            //接下来接收到服务端返回的响应
            BufferedInputStream bufferedInputStream =
                    new BufferedInputStream(inputStream);
            byte[] bytes = StreamUtil.streamByteArray(bufferedInputStream);
            String pathname = StreamUtil.streamToString(bufferedInputStream);
            String path = "e://" + fileName + ".mp3";
            //然后将其下载到磁盘中
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
            bos.write(bytes);

            System.out.println("客户端下载完毕...");
            //关闭对应的流
            bufferedOutputStream.close();
            bufferedInputStream.close();
            bos.close();
        }finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPFileClint01 tcpFileClint01 = new TCPFileClint01();
        tcpFileClint01.start();
    }


}
